import { dom, DOMNode, InitFun } from "../mve-DOM/index";
import { EmptyFun, mve} from "../mve/util";




export type MenuFun=(me:mve.LifeModel,x:{})=>{
	element:DOMNode;
	init?:InitFun;
}

export function menu(fun:MenuFun){
  const body=document.body;
  const show=mve.valueOf(false);
  const top=mve.valueOf(0);
  const left=mve.valueOf(0);
	const menu=dom.root(function(me){

		var render_object=fun(me,{});
		var p=render_object.element;

		p.type=p.type||"div";
		p.style=p.style||{};
		p.event=p.event||{};
		const style=p.style;
		const action=p.event;

		if(typeof(style)=='function'){
			p.style=function(){
				const s=style()
				s.position='absolute'
				s.display=show()?"":"none"
				s.top=top()+"px"
				s.left=left()+'px'
				return s
			}
		}else{
			style.position="absolute";
			style.display=function(){
				return show()?"":"none";
			}
			style.top=function(){
				return top()+"px";
			}
			style.left=function(){
				return left()+"px";
			}
		}

		function hide(){
			show(false);
		};

		p.init=function(e,me){
			mb.DOM.addEvent(document,"click",hide);
			const destroy=render_object.init?.(e,me)
			return function(){
				mb.DOM.removeEvent(document,"click",hide);
				if(destroy){
					destroy()
				}
			}
		}
		return p
	});
	let need_init=true;

	let menuInitResult:EmptyFun|void
	return {
		show(x:number,y:number){
			if(need_init){
				body.appendChild(menu.element);
				menuInitResult=menu.init?.()
				need_init=false;
			}
			left(x);
			top(y);
			show(true);
		},
		hide(){
			show(false);
		},
		destroy(){
			if(!need_init){
				//已经初始化过了
				if(menuInitResult){
					menuInitResult()
				}
				body.removeChild(menu.element);
			}
		}
	};
}